package servlets;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cmput391.src.queries.DBConnector;
import cmput391.src.queries.SecurityQueries;
import cmput391.src.queries.UserManagementQueries;

/**
 * Servlet implementation class JsonDoctorList
 */
@WebServlet("/JsonUsersList")
public class JsonUsersList extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public JsonUsersList() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String userClass = (request.getParameter("userClass")).trim();
		
		DBConnector dbConnect = new DBConnector();
		SecurityQueries security = null;
		
		String term = request.getParameter("term").toLowerCase();

		try {
			security = new SecurityQueries(dbConnect.getConnection());
			UserManagementQueries umq = new UserManagementQueries(dbConnect.getConnection(), security);
			ArrayList<String> allUsers = new ArrayList<String>();
			allUsers.addAll(umq.getAllOfClass(userClass));			
			String jsonUsers = "[";
			int i=1;
			for (String user : allUsers) {
				String lowerCaseUser = user.toLowerCase();
				if (lowerCaseUser.contains(term)) {
					if (i > 1)
						jsonUsers +=", ";					
					jsonUsers += "\""+user+"\"";

					i++;
				}
			}
					
			jsonUsers += "]";
			System.out.println(jsonUsers);
			response.setContentType("application/json");
			PrintWriter out = response.getWriter();
			out.print(jsonUsers);
			out.flush();
		}
		catch (Exception e) {
			response.sendError(500);
			request.getRequestDispatcher("addRecord.jsp").forward(request, response);				
		    e.printStackTrace();
		}
	}

}
